﻿using System;
using System.Collections;
using UnityEngine;

namespace YunHao
{
    /// <summary>
    /// 自定义携程，支持暂停、继续、停止以及对应事件
    /// </summary>
    public class InterruptCoroutine
    {
        /// <summary>
        /// 结束事件
        /// </summary>
        public event Action<bool> OnFinished;
        /// <summary>
        /// 开始事件
        /// </summary>
        public event Action OnStart;

        public bool Running
        {
            get { return _running; }
        }
        public bool Stoped
        {
            get { return _stopped; }
        }
        public bool Paused
        {
            get { return _paused; }
        }
        /// <summary>
        /// 携程在运行中
        /// </summary>
        private bool _running;
        /// <summary>
        /// 携程停止
        /// </summary>
        private bool _stopped;
        /// <summary>
        /// 携程暂停
        /// </summary>
        private bool _paused;
        /// <summary>
        /// 携程程序
        /// </summary>
        private IEnumerator _corountine;
        /// <summary>
        /// 携程运行的<typeparamref name="MonoBehaviour"/>
        /// </summary>
        private MonoBehaviour _mono;

        public InterruptCoroutine(IEnumerator e, MonoBehaviour mono)
        {
            _corountine = e;
            _mono = mono;
        }

        /// <summary>
        /// 启动
        /// </summary>
        public void Start()
        {
            _running = true;
            _paused = false;
            _mono.StartCoroutine(CallWrapper());
        }

        /// <summary>
        /// 停止
        /// </summary>
        public void Stop()
        {
            _running = false;
            _stopped = true;
        }

        /// <summary>
        /// 暂停
        /// </summary>
        public void Pause()
        {
            _paused = true;
        }

        /// <summary>
        /// 继续运行
        /// </summary>
        public void Continue()
        {
            _paused = false;
        }

        /// <summary>
        /// 携程时间
        /// </summary>
        /// <returns></returns>
        IEnumerator CallWrapper()
        {
            IEnumerator e = _corountine;
            if (null != OnStart)
                OnStart();
            while (_running)
            {
                if (_paused)
                    yield return null;
                else
                {
                    if (e != null && e.MoveNext())
                        yield return e.Current;
                    else
                        _running = false;
                }
            }
            if (null != OnFinished)
                OnFinished(_stopped);
        }
    }
}
